package pkg

import (
	"crypto/md5"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"os/exec"
	"regexp"
	"runtime"
	"strings"
)

const (
	MD5_PREFIX = "jkfldfsf" //MD5加密前缀字符串
	DefaultPwd = "123456"
)

func Md5(str string) string {
	data := []byte(str)
	return fmt.Sprintf("%x", md5.Sum(data))
}

func UUID() string {

	id := uuid.NewV4()
	return strings.ReplaceAll(id.String(), "-", "")

}

func FormatPwd(pwd string) string {
	return MD5_PREFIX + pwd
}

func ErrorFormat(err interface{}) string {
	switch v := err.(type) {
	case error:
		return v.Error()
	default:
		return err.(string)
	}
}

//

func IsChinese(res string) bool {

	reg := regexp.MustCompile(`^[\u4e00-\u9fa5]{1,4}$`)
	return reg.MatchString(res)

}

var commands = map[string][]string{
	"windows": {"cmd", "/c", "start"},
	"darwin":  {"open"},
	"linux":   {"xdg-open"},
}

func OpenBrowser(uri string) error {
	run, ok := commands[runtime.GOOS]
	if !ok {
		return fmt.Errorf("don't know how to open things on %s platform", runtime.GOOS)
	}
	run = append(run, uri)

	cmd := exec.Command(run[0], run[1:]...)
	return cmd.Start()
}
func IsMobile(userAgent string) bool {
	if len(userAgent) == 0 {
		return false
	}

	isMobile := false
	mobileKeywords := []string{"Mobile", "Android", "Silk/", "Kindle",
		"BlackBerry", "Opera Mini", "Opera Mobi"}

	for i := 0; i < len(mobileKeywords); i++ {
		if strings.Contains(userAgent, mobileKeywords[i]) {
			isMobile = true
			break
		}
	}

	return isMobile
}
